package com.slipper.sfts.redis;

import com.slipper.common.util.GsonUtil;
import com.slipper.sfts.websocket.MessageVO;
import com.slipper.sfts.websocket.WebsocketManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

public class RedisReceiver implements MessageListener {
    private static final Logger logger = LoggerFactory.getLogger(RedisReceiver.class);

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String topic = new String(pattern);
        String channel = new String(message.getChannel());
        String body = new String(message.getBody());
        logger.info("接收到消息回调，topic: {}, channel: {}, body: {}", topic, channel, body);

        if (channel.startsWith("on_tick_callback_")) {
            MessageVO vo = new MessageVO();
            vo.setType("tick");
            vo.setData(body);
            String memberId = channel.replaceFirst("on_tick_callback_", "");
            WebsocketManager.sendMessage(memberId, GsonUtil.toJson(vo));
        } else if (channel.startsWith("on_tick_list_callback_")) {
            MessageVO vo = new MessageVO();
            vo.setType("tick_list");
            vo.setData(body);
            String memberId = channel.replaceFirst("on_tick_list_callback_", "");
            WebsocketManager.sendMessage(memberId, GsonUtil.toJson(vo));
        } else if (channel.startsWith("on_member_message_")) {
            MessageVO vo = new MessageVO();
            vo.setType("message");
            vo.setData(body);
            String memberId = channel.replaceFirst("on_member_message_", "");
            WebsocketManager.sendMessage(memberId, GsonUtil.toJson(vo));
        }
    }
}
